package com.shushan.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.shushan.base.Constants;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;

/**
 * @ClassName: ImageUtils
 * @Desciption: 图片工具类
 * @author: yichaohua
 * @date: 2018-01-26
 */
public class ImageUtils {

    private static final String TAG = "ImageUtils";

    private static final Pattern ABSOLUTE_URL = Pattern.compile("\\A[a-z0-9.+-]+://.*", Pattern.CASE_INSENSITIVE);

    public static void loadImageView(Context context, String url, ImageView imageView) {
        if (TextUtils.isEmpty(url) || imageView == null || context == null) {
            return;
        }

        String loadUrl;
        if (isAbsoluteUrl(url)) {
            loadUrl = url;
        } else {
            loadUrl = BuildConfig.imgBaseUrl + url;
        }

        Log.i(TAG, "loadUrl=" + loadUrl);
        if(isContextValide(context)) {
            Glide.with(context).load(loadUrl).into(imageView);
        }
    }

    public static void loadAdvertNoCacheImg(Context context, int id, ImageView imageView) {
        if (id <= 0 || imageView == null || context == null) {
            return;
        }

        if(isContextValide(context)) {
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.NONE);
            Glide.with(context).load(Constants.ADVERT_DOWNLOAD_FOLDER + id + ".png").apply(options).into(imageView);
        }
    }

    public static void loadWXImageView(Context context, String url, ImageView imageView) {
        if (TextUtils.isEmpty(url) || imageView == null || context == null) {
            return;
        }

        String loadUrl;
        if (isAbsoluteUrl(url)) {
            loadUrl = url;
        } else {
            loadUrl = BuildConfig.wxUpImgBaseUrl + url;
        }
        if(isContextValide(context)) {
            Glide.with(context).load(loadUrl).into(imageView);
        }
    }

    public static void loadGifImageView(Context context, String url, ImageView imageView) {
        if (TextUtils.isEmpty(url) || imageView == null || context == null) {
            return;
        }

        String loadUrl;
        if (isAbsoluteUrl(url)) {
            loadUrl = url;
        } else {
            loadUrl = BuildConfig.wxUpImgBaseUrl + url;
        }
        if(isContextValide(context)) {
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
            Glide.with(context).asGif().load(loadUrl).apply(options).into(imageView);
        }
    }

    public static void loadImageNoBg(Context context, String url, ImageView imageView) {
        if (TextUtils.isEmpty(url) || imageView == null || context == null) {
            return;
        }

        String loadUrl;
        if (isAbsoluteUrl(url)) {
            loadUrl = url;
        } else {
            loadUrl = BuildConfig.imgBaseUrl + url;
        }
        if(isContextValide(context)) {
            Glide.with(context).load(loadUrl).into(imageView);
        }
    }

    public static void loadImagePlace(Context context, int resourceId,String url, ImageView imageView) {
        if (TextUtils.isEmpty(url) || imageView == null || context == null) {
            return;
        }

        String loadUrl;
        if (isAbsoluteUrl(url)) {
            loadUrl = url;
        } else {
            loadUrl = BuildConfig.imgBaseUrl + url;
        }
        if(isContextValide(context)) {
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .placeholder(resourceId);
            Glide.with(context).load(loadUrl).apply(options).into(imageView);
        }
    }

    public static void loadImgFile(Context context, File imgFile,ImageView imageView){
        if (imgFile == null || imageView == null || context == null) {
            return;
        }
        if(isContextValide(context)) {
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
            Glide.with(context).asGif().load(imgFile).apply(options).into(imageView);
        }
    }

    public static boolean isAbsoluteUrl(String url) {
        if (url == null) {
            return false;
        }

        return ABSOLUTE_URL.matcher(url).matches();
    }

    /**
     * 将bmp转换为字节数组
     *
     * @param bmp
     * @param needRecycle
     * @return
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 获取当前屏幕截图，不包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap screenShotWithoutStatusBar(Activity activity) {
        //通过window的源码可以看出：检索顶层窗口的装饰视图，可以作为一个窗口添加到窗口管理器
        View view = activity.getWindow().getDecorView();
        //启用或禁用绘图缓存
        view.setDrawingCacheEnabled(true);
        //创建绘图缓存
        view.buildDrawingCache();
        //拿到绘图缓存
        Bitmap bitmap = view.getDrawingCache();

        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

        //状态栏高度
        int statusBarHeight = frame.top;
        int width = DensityUtil.getScreenWidth(activity);
        int height = DensityUtil.getScreenHeight(activity);

        Bitmap bp = null;
        bp = Bitmap.createBitmap(bitmap, 0, 0, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return bp;
    }

    private static Bitmap map;
    public static Bitmap getNetwrokBitmap(final String urlpath) {
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        String loadUrl;
                        if (isAbsoluteUrl(urlpath)) {
                            loadUrl = urlpath;
                        } else {
                            loadUrl = BuildConfig.imgBaseUrl + urlpath;
                        }
                        try {
                            URL url = new URL(loadUrl);
                            URLConnection conn = url.openConnection();
                            conn.connect();
                            InputStream in;
                            in = conn.getInputStream();
                            map = BitmapFactory.decodeStream(in);
                        }catch (IOException ioe){
                            ioe.printStackTrace();
                        }
                    }
                }
        ).start();
        try {
            Thread.sleep(800);
        }catch (InterruptedException ie){
            ie.printStackTrace();
        }finally {
            return map;
        }
    }

    public static void releaseImageViewResouce(ImageView imageView) {
        if (imageView == null) return;
        Drawable drawable = imageView.getDrawable();
        if (drawable != null && drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
        imageView = null;
    }

    private static boolean isContextValide(Context context){
        if(context == null){
            Log.i(TAG,"context == null");
            return false;
        }
        if(context instanceof Activity){
            if(((Activity)context).isDestroyed()){
                Log.i(TAG,"activity isDestroyed");
                return false;
            }
        }
        return true;
    }

}
